package com.lagou;

import com.lagou.controller.DBUtil;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.ChildData;
import org.apache.curator.framework.recipes.cache.TreeCache;
import org.apache.curator.framework.recipes.cache.TreeCacheEvent;
import org.apache.curator.framework.recipes.cache.TreeCacheListener;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class ZkDatabaseApplication {

    private static Logger logger = LoggerFactory.getLogger(ZkDatabaseApplication.class);

    public static void main(String[] args) throws Exception {
        SpringApplication.run(ZkDatabaseApplication.class, args);
        initZk("mysql");
    }

    private static void refresh(String value) {
        if (value == null) {
            return;
        }
        String[] split = value.split(",");
        DBUtil.setDruidDataSource(split[0], split[1], split[2], split[3]);
    }

    private static void initZk(String key) throws Exception {
        //不使用fluent编程风格
        RetryPolicy exponentialBackoffRetry = new ExponentialBackoffRetry(10, 1);

        // 使用fluent编程风格
        CuratorFramework client = CuratorFrameworkFactory.builder()
                .connectString("127.0.0.1:2181")
                .sessionTimeoutMs(50000)
                .connectionTimeoutMs(30000)
                .retryPolicy(exponentialBackoffRetry)
                .namespace("database")  // 独立的命名空间 /base
                .build();

        client.start();
        System.out.println("会话创建了");
        // 创建节点
        String path = "/" + key;
        TreeCache treeCache = new TreeCache(client, path);
        treeCache.getListenable().addListener(new TreeCacheListener() {
            @Override
            public void childEvent(CuratorFramework client, TreeCacheEvent event) throws Exception {
                ChildData eventData = event.getData();
                switch (event.getType()) {
                    case NODE_ADDED:
                        logger.warn(path + "节点添加" + eventData.getPath() + "\t添加数据为：" + new String(eventData.getData()));
                        refresh(new String(eventData.getData()));
                        break;
                    case NODE_UPDATED:
                        logger.warn(eventData.getPath() + "节点数据更新\t更新数据为：" + new String(eventData.getData()) + "\t版本为：" + eventData.getStat().getVersion());
                        refresh(new String(eventData.getData()));
                        break;
                    case NODE_REMOVED:
                        logger.warn(eventData.getPath() + "节点被删除");
                        throw new RuntimeException("database/mysql is null");
                    default:
                        break;
                }
            }
        });
        treeCache.start();
    }

}
